﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ColorPicker;
using GalaSoft.MvvmLight.Messaging;
using Microsoft.Win32;
using Microsoft.Windows.Controls.Ribbon;
using Microsoft.WindowsAPICodePack.Dialogs;
using TeacherLeftHand.Messages;
using TeacherLeftHand.Model;
using TeacherLeftHand.ViewModel;

namespace TeacherLeftHand.View
{
    /// <summary>
    /// Interaction logic for CreateNewKIView.xaml
    /// </summary>
    public partial class CreateNewKIView : Window
    {
        public CreateNewKIView()
        {
            InitializeComponent();

            Closing += (s, e) => ViewModelLocator.ClearCreateNewKI();

            Loaded += (s, e) => DataContext = ViewModelLocator.CreateNewKIStatic;
            
            Messenger.Default.Register<CloseWindowMessage>(this, msg => Close());
        }


        #region Undo/Redo/Cut/Copy/Paste/Delete/Select All

        public void UndoMenuItem_Click(System.Object sender, RoutedEventArgs e)
        {
            rtbKIContent.Focus();
            rtbKIContent.Undo();
        }

        public void RedoMenuItem_Click(System.Object sender, RoutedEventArgs e)
        {
            rtbKIContent.Focus();
            rtbKIContent.Redo();
        }

        public void CutMenuItem_Click(System.Object sender, RoutedEventArgs e)
        {
            rtbKIContent.Focus();
            rtbKIContent.Cut();
        }

        public void CutParagraphMenuItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (rtbKIContent.Selection.IsEmpty)
                {
                    if (rtbKIContent.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(rtbKIContent.CaretPosition.Paragraph.ElementStart, rtbKIContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            rtbKIContent.Selection.Select(range.Start, range.End);
                            rtbKIContent.Cut();
                        }
                    }
                }
                else
                {
                    EditingCommands.MoveToLineStart.Execute(null, rtbKIContent);
                    if (rtbKIContent.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(rtbKIContent.CaretPosition.Paragraph.ElementStart, rtbKIContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            rtbKIContent.Selection.Select(range.Start, range.End);
                            rtbKIContent.Cut();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            e.Handled = true;
        }

        public void CutLineMenuItem_Click(object sender, RoutedEventArgs e)
        {
            EditingCommands.MoveToLineStart.Execute(null, rtbKIContent);
            EditingCommands.SelectToLineEnd.Execute(null, rtbKIContent);
            rtbKIContent.Cut();
            e.Handled = true;
        }

        public void CopyMenuItem_Click(System.Object sender, RoutedEventArgs e)
        {
            rtbKIContent.Focus();
            rtbKIContent.Copy();
        }

        public void CopyParagraphMenuItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (rtbKIContent.Selection.IsEmpty)
                {
                    if (rtbKIContent.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(rtbKIContent.CaretPosition.Paragraph.ElementStart, rtbKIContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            rtbKIContent.Selection.Select(range.Start, range.End);
                            rtbKIContent.Copy();
                        }
                    }
                }
                else
                {
                    EditingCommands.MoveToLineStart.Execute(null, rtbKIContent);
                    if (rtbKIContent.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(rtbKIContent.CaretPosition.Paragraph.ElementStart, rtbKIContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            rtbKIContent.Selection.Select(range.Start, range.End);
                            rtbKIContent.Copy();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            e.Handled = true;
        }

        public void CopyLineMenuItem_Click(object sender, RoutedEventArgs e)
        {
            EditingCommands.MoveToLineStart.Execute(null, rtbKIContent);
            EditingCommands.SelectToLineEnd.Execute(null, rtbKIContent);
            rtbKIContent.Copy();
            e.Handled = true;
        }

        #region Paste

        public void PasteMenuItem_Click(System.Object sender, RoutedEventArgs e)
        {
            rtbKIContent.Focus();
            rtbKIContent.Paste();
        }

        public void PasteTextButton_Click(object sender, RoutedEventArgs e)
        {
            rtbKIContent.CaretPosition.InsertTextInRun(Clipboard.GetText());
            e.Handled = true;
        }

        #endregion

        public void DeleteMenuItem_Click(object sender, RoutedEventArgs e)
        {
            EditingCommands.Delete.Execute(null, rtbKIContent);
        }

        public void DeleteParagraphMenuItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (rtbKIContent.Selection.IsEmpty)
                {
                    if (rtbKIContent.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(rtbKIContent.CaretPosition.Paragraph.ElementStart, rtbKIContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            rtbKIContent.Selection.Select(range.Start, range.End);
                            EditingCommands.Delete.Execute(null, rtbKIContent);
                        }
                    }
                }
                else
                {
                    EditingCommands.MoveToLineStart.Execute(null, rtbKIContent);
                    if (rtbKIContent.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(rtbKIContent.CaretPosition.Paragraph.ElementStart, rtbKIContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            rtbKIContent.Selection.Select(range.Start, range.End);
                            EditingCommands.Delete.Execute(null, rtbKIContent);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            e.Handled = true;
        }

        public void DeleteLineMenuItem_Click(object sender, RoutedEventArgs e)
        {
            EditingCommands.MoveToLineStart.Execute(null, rtbKIContent);
            EditingCommands.SelectToLineEnd.Execute(null, rtbKIContent);
            EditingCommands.Delete.Execute(null, rtbKIContent);
            e.Handled = true;
        }

        public void SelectAllMenuItem_Click(System.Object sender, RoutedEventArgs e)
        {
            rtbKIContent.Focus();
            rtbKIContent.SelectAll();
        }

        public void SelectParagraphMenuItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (rtbKIContent.Selection.IsEmpty)
                {
                    if (rtbKIContent.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(rtbKIContent.CaretPosition.Paragraph.ElementStart, rtbKIContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            rtbKIContent.Selection.Select(range.Start, range.End);
                        }
                    }
                }
                else
                {
                    EditingCommands.MoveToLineStart.Execute(null, rtbKIContent);
                    if (rtbKIContent.CaretPosition.Paragraph != null)
                    {
                        var range = new TextRange(rtbKIContent.CaretPosition.Paragraph.ElementStart, rtbKIContent.CaretPosition.Paragraph.ElementEnd);
                        if (!range.IsEmpty)
                        {
                            rtbKIContent.Selection.Select(range.Start, range.End);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            e.Handled = true;
        }

        public void SelectLineMenuItem_Click(object sender, RoutedEventArgs e)
        {
            EditingCommands.MoveToLineStart.Execute(null, rtbKIContent);
            EditingCommands.SelectToLineEnd.Execute(null, rtbKIContent);
            e.Handled = true;
        }

        #endregion
        #region --ViewMenu




        private WindowState _fullscreensetting = System.Windows.WindowState.Normal;
        //public void FullScreenMenuItem_Click(object sender, RoutedEventArgs e)
        //{
        //    if (FullscreenMenuItem.IsPressed)
        //    {
        //        FullscreenMenuItem.IsChecked = false;
        //        Topmost = false;
        //        WindowStyle = System.Windows.WindowStyle.SingleBorderWindow;
        //        WindowState = _fullscreensetting;
        //    }
        //    else
        //    {
        //        FullscreenMenuItem.IsChecked = true;
        //        _fullscreensetting = WindowState;
        //        if (WindowState == System.Windows.WindowState.Maximized)
        //        {
        //            WindowState = System.Windows.WindowState.Normal;
        //        }
        //        WindowStyle = System.Windows.WindowStyle.None;
        //        Topmost = true;
        //        WindowState = System.Windows.WindowState.Maximized;
        //    }
        //}

        #endregion

        #region Image

        public void ImageButton_Click(object sender, RoutedEventArgs e)
        {
            var id = new ImageDialog();
            id.Owner = this;
            id.ShowDialog();
            if (id.Res == "OK")
            {
                rtbKIContent.Focus();
                var caretPos = rtbKIContent.CaretPosition;
                foreach (var i in id.Images)
                {
                    
                    var img = new Image();
                    var b = new BitmapImage();
                    b.BeginInit();
                    b.UriSource = new Uri(i);
                    b.EndInit();
                    img.Height = b.Height;
                    img.Width = b.Width;
                    img.Source = b;
                    var inline = new InlineUIContainer(img, caretPos);
                   
                }
            }
        }

        #endregion

        #region Link



        #endregion

        #region Text File

        public void TextFileButton_Click(object sender, RoutedEventArgs e)
        {
            if (MS.WindowsAPICodePack.Internal.CoreHelpers.RunningOnVista || MS.WindowsAPICodePack.Internal.CoreHelpers.RunningOnWin7)
            {
                var o = new CommonOpenFileDialog();
                var f = new CommonFileDialogFilter("Text Document", "*.txt");
                o.Filters.Add(f);
                if (o.ShowDialog() == CommonFileDialogResult.Ok)
                {
                    rtbKIContent.CaretPosition.InsertTextInRun(My.MyWpfExtension.Computer.FileSystem.ReadAllText(o.FileName));
                }
            }
            else
            {
                var o = new OpenFileDialog();
                o.Filter = "Text Document|*.txt";
                if (o.ShowDialog() == true)
                {
                    rtbKIContent.CaretPosition.InsertTextInRun(My.MyWpfExtension.Computer.FileSystem.ReadAllText(o.FileName));
                }
            }
        }

        #endregion

        #region Table

        public void TableButton_Click(object sender, RoutedEventArgs e)
        {
            var tableDialog = new TableDialog();
            tableDialog.Owner = this;
            tableDialog.ShowDialog();
            if (tableDialog.Res == "OK")
            {
                var t = new Table();
                int @int = Convert.ToInt32(tableDialog.RowsTextBox.Text);
                int int2 = Convert.ToInt32(tableDialog.CellsTextBox.Text);
                while (@int != 0)
                {
                    var trg = new TableRowGroup();
                    var tr = new TableRow();
                    while (int2 != 0)
                    {
                        var tc = new TableCell();
                        if (tableDialog.BorderColor != null)
                        {
                            tc.BorderBrush = tableDialog.BorderColor;
                        }
                        else
                        {
                            tc.BorderBrush = Brushes.LightGray;
                        }
                        tc.BorderThickness = new Thickness(2, 2, 2, 2);
                        tr.Cells.Add(tc);
                        int2--;
                    }
                    int2 = Convert.ToInt32(tableDialog.CellsTextBox.Text);
                    trg.Rows.Add(tr);
                    t.RowGroups.Add(trg);
                    @int--;
                }
                t.BorderBrush = Brushes.WhiteSmoke;
                if (rtbKIContent.CaretPosition.Paragraph != null)
                {
                    if (rtbKIContent.CaretPosition.Paragraph.PreviousBlock != null)
                    {
                        rtbKIContent.Document.Blocks.InsertAfter(rtbKIContent.CaretPosition.Paragraph.PreviousBlock, t);
                    }
                    else if (rtbKIContent.CaretPosition.Paragraph.SiblingBlocks != null)
                    {
                        rtbKIContent.Document.Blocks.InsertAfter(rtbKIContent.CaretPosition.Paragraph.SiblingBlocks.FirstBlock, t);
                    }

                }

            }
        }

        #endregion

        #region Horizontal Line

        public void HorizontalLineButton_Click(object sender, RoutedEventArgs e)
        {
            var d = new InsertLineDialog();
            d.Owner = this;
            d.ShowDialog();
            if (d.Res == "OK")
            {
                var line = new Separator();
                var inline = new InlineUIContainer();
                line.Background = Brushes.Gray;
                line.Width = d.LineWidth;
                line.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                inline.Child = line;
                if (rtbKIContent.CaretPosition.Paragraph != null)
                {
                    rtbKIContent.CaretPosition.Paragraph.Inlines.Add(inline);
                }
            }
        }

        #endregion

        #region --FormatMenuItem

        public void ClearFormattingButton_Click(object sender, RoutedEventArgs e)
        {
            rtbKIContent.Selection.ClearAllProperties();
            UpdateSelected();
        }
        #endregion
        #region Font/Font Size/Font Color/Hightlight Color

        public void FontButton_Click(object sender, RoutedEventArgs e)
        {
            var d = new FontDialog();
            d.Owner = this;
            d.ShowDialog();
            if (d.Res == "OK")
            {
                if (rtbKIContent.Selection != null)
                {
                    rtbKIContent.Selection.ApplyPropertyValue(TextElement.FontFamilyProperty, d.font);
                }
            }
        }

        public void FontSizeButton_Click(object sender, RoutedEventArgs e)
        {
            var d = new FontSizeDialog();
            d.Owner = this;
            d.ShowDialog();
            if (d.Res == "OK" && d.Number > 0)
            {
                rtbKIContent.Selection.ApplyPropertyValue(TextElement.FontSizeProperty, d.Number);
            }
        }

        public void FontColorButton_Click(object sender, RoutedEventArgs e)
        {
            var d = new ColorDialog();
            var c = new SolidColorBrush();
            d.Owner = this;
            if (d.ShowDialog() == true)
            {
                c.Color = d.SelectedColor;
                rtbKIContent.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, c);
            }
        }

        public void HighlightColorButton_Click(object sender, RoutedEventArgs e)
        {
            var d = new ColorDialog();
            var c = new SolidColorBrush();
            //d.Owner = this;
            if (d.ShowDialog() == true)
            {
                c.Color = d.SelectedColor;
                rtbKIContent.Selection.ApplyPropertyValue(TextElement.BackgroundProperty, c);
            }
        }

        #endregion

        private void SubscriptButton_Click(object sender, RoutedEventArgs e)
        {
            rtbKIContent.ToggleSubscript();
        }

        private void SuperscriptButton_Click(object sender, RoutedEventArgs e)
        {
            rtbKIContent.ToggleSuperscript();
        }
        #region Blod/Italic/Underline/Strikethrough

        public void BoldMenuItem_Click(System.Object sender, RoutedEventArgs e)
        {
            EditingCommands.ToggleBold.Execute(null, rtbKIContent);
        }

        public void ItalicMenuItem_Click(object sender, RoutedEventArgs e)
        {
            EditingCommands.ToggleItalic.Execute(null, rtbKIContent);
        }

        public void UnderlineMenuItem_Click(object sender, RoutedEventArgs e)
        {
            EditingCommands.ToggleUnderline.Execute(null, rtbKIContent);
        }

        public void StrikethroughButton_Click(object sender, RoutedEventArgs e)
        {
            //rtbKIContent.ToggleStrikethrough();
            rtbKIContent.ToggleStrikethrough();
        }

        #endregion



        #region Indent More/Indent Less

        public void IndentMoreButton_Click(object sender, RoutedEventArgs e)
        {
            EditingCommands.IncreaseIndentation.Execute(null, rtbKIContent);
        }

        public void IndentLessButton_Click(object sender, RoutedEventArgs e)
        {
            EditingCommands.DecreaseIndentation.Execute(null, rtbKIContent);
        }

        #endregion

        #region Bullet List/Number List

        public void BulletListMenuItem_Click(object sender, RoutedEventArgs e)
        {
            EditingCommands.ToggleBullets.Execute(null, rtbKIContent);
        }

        public void NumberListMenuItem_Click(object sender, RoutedEventArgs e)
        {
            EditingCommands.ToggleNumbering.Execute(null, rtbKIContent);
        }

        #endregion

        #region Align Left/Center/Right/Justify

        public void AlignLeftMenuItem_Click(System.Object sender, RoutedEventArgs e)
        {
            EditingCommands.AlignLeft.Execute(null, rtbKIContent);
        }

        public void AlignCenterMenuItem_Click(System.Object sender, RoutedEventArgs e)
        {
            EditingCommands.AlignCenter.Execute(null, rtbKIContent);
        }

        public void AlignRightMenuItem_Click(System.Object sender, RoutedEventArgs e)
        {
            EditingCommands.AlignRight.Execute(null, rtbKIContent);
        }

        public void AlignJustifyMenuItem_Click(object sender, RoutedEventArgs e)
        {
            EditingCommands.AlignJustify.Execute(null, rtbKIContent);
        }

        #endregion

        #region Line Spacing

        public void LineSpacingButton_Click(object sender, RoutedEventArgs e)
        {
            var d = new LineSpacingDialog();
            d.Owner = this;
            d.ShowDialog();
            if (d.Res == "OK")
            {
                try
                {
                    if (rtbKIContent.CaretPosition.Paragraph != null)
                    {
                        rtbKIContent.CaretPosition.Paragraph.LineHeight = d.number;
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Error");
                }
            }
        }

        #endregion

        #region ltr/rtl

        public void LefttoRightButton_Click(object sender, RoutedEventArgs e)
        {
            rtbKIContent.Document.FlowDirection = FlowDirection.LeftToRight;
        }

        public void RighttoLeftButton_Click(object sender, RoutedEventArgs e)
        {
            rtbKIContent.Document.FlowDirection = FlowDirection.RightToLeft;
        }

        #endregion


        private void UpdateSelected()
        {


            if (rtbKIContent.CanUndo)
            {
                CommonUndoButton.IsEnabled = true;
                CommonUndoButton.IsEnabled = true;
            }
            else
            {
                CommonUndoButton.IsEnabled = false;
                CommonUndoButton.IsEnabled = false;
            }
            if (rtbKIContent.CanRedo)
            {
                CommonRedoButton.IsEnabled = true;
                CommonRedoButton.IsEnabled = true;
            }
            else
            {
                CommonRedoButton.IsEnabled = false;
                CommonRedoButton.IsEnabled = false;
            }
            if (My.MyWpfExtension.Computer.Clipboard.ContainsText())
            {
                CommonPasteButton.IsEnabled = true;
                CommonPasteButton.ToolTipFooterTitle = "Preview:";
                CommonPasteButton.ToolTipFooterDescription = My.MyWpfExtension.Computer.Clipboard.GetText();
                CommonPasteButton.IsEnabled = true;
                CommonPasteButton.ToolTipFooterTitle = "Preview:";
                CommonPasteButton.ToolTipFooterDescription = My.MyWpfExtension.Computer.Clipboard.GetText();
                CommonPasteTextMenuItem.IsEnabled = true;
            }
            else if (My.MyWpfExtension.Computer.Clipboard.ContainsImage())
            {
                //TODO: add paste image support
            }
            else
            {
                CommonPasteTextMenuItem.IsEnabled = false;
                CommonPasteButton.IsEnabled = false;
                CommonPasteButton.ToolTipFooterTitle = null;
                CommonPasteButton.ToolTipFooterDescription = null;
                CommonPasteButton.IsEnabled = false;
                CommonPasteButton.ToolTipFooterTitle = null;
                CommonPasteButton.ToolTipFooterDescription = null;
            }

        }

        private void CloseMenuItem_Click(object sender, RoutedEventArgs e)
        {
           this.Close();
        }
    }

}
